<?php

/*
 * Copyright (C) 2009 - 2011 Pham Cong Dinh
 *
 * This file is part of Spica.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
include_once 'spica/core/service/DatabaseService.php';
include_once 'spica/core/utils/BaseUtils.php';
include_once 'spica/core/utils/ContainerUtils.php';

/**
 * SpicaDocsNoteService provides operations for creating and/or modifying Spica Docs note.
 *
 * namespace spica\docs\service\DocsNote;
 *
 * @category   spica
 * @package    docs
 * @subpackage service
 * @author     Pham Cong Dinh <pcdinh at phpvietnam dot net>
 * @since      Version 0.3
 * @since      May 12, 2009
 * @copyright  Pham Cong Dinh (http://www.phpvietnam.net)
 * @license    http://www.gnu.org/licenses/lgpl-3.0.txt
 * @version    $Id: SpicaDocsNoteService.php 1869 2011-01-07 18:55:25Z pcdinh $
 */
class SpicaDocsNoteService extends SpicaDatabaseService
{
    /**
     * Data source.
     *
     * @var Pone_Database_Connection
     */
    public $ds;

    /**
     * Constructs an object of <code>SpicaDocsNoteService</code> with a data source
     * alias name.
     *
     * @param string $alias Data source alias name
     */
    public function __construct($alias = 'spicadocs')
    {
        parent::__construct($alias);
    }

    /**
     * Creates a docs note.
     *
     * @throws Exception if the manual page is not defined in manual table
     * @throws SpicaDatabaseException if there is any problem with database connection or query
     * @param  SpicaDocsNoteForm $form
     * @return bool
     */
    public function create($form)
    {
        $pageId   = $form->get('page_id');

        if (false === $this->existsPage($pageId))
        {
            throw new Exception('The current page ID '.$form->get('page_id').' is not defined in manual page table. ');
        }

        $username = $this->ds->quote($form->get('username'));
        $note     = $this->ds->quote($form->get('note'));

        $sql = sprintf('INSERT INTO notes (
                          note_username, note_content, page_id, note_dtime, note_status
                        ) VALUES (
                           \'%s\', \'%s\', \'%s\', \'%s\', 1
                        )', $username, $note, $pageId, date('Y-m-d H:i:s', time()));

        $stmt = $this->ds->createStatement();
        $stmt->executeUpdate($sql);
        return true;
    }

    /**
     * Identifies a manual page ID by a $section and a $pageName.
     *
     * @throws Exception if the manual page is not defined in manual table
     * @throws SpicaDatabaseException if there is any problem with database connection or query
     * @param  string $section
     * @param  string $pageName
     * @return int
     */
    public function findPageId($section, $pageName)
    {
        $section  = $this->ds->quote($section);
        $pageName = $this->ds->quote($pageName);

        // Module, controller, action should not contain special characters like '
        $sql = sprintf('SELECT page_id
                        FROM manual_pages
                        WHERE page_section  = %s
                        AND page_name       = %s', "'".$section."'", "'".$pageName."'");

        $stmt   = $this->ds->createStatement();
        $pageId = $stmt->fetchOne($sql);
        $stmt->close();

        if (null === $pageId)
        {
            throw new Exception('The current page '.SpicaContext::getFullUrl().' is not defined in manual page table. ');
        }

        return $pageId;
    }

    /**
     * Checks if a manual page ID exists.
     *
     * @throws SpicaDatabaseException if there is any problem with database connection or query
     * @param  string $pageId
     * @return bool
     */
    public function existsPage($pageId)
    {
        // Module, controller, action should not contain special characters like '
        $sql    = sprintf('SELECT page_id FROM manual_pages
                           WHERE page_id = %s', $pageId);
        $stmt   = $this->ds->createStatement();
        $pageId = $stmt->fetchOne($sql);
        $stmt->close();

        return (bool) $pageId;
    }

    /**
     * Finds relevant notes by a page ID.
     *
     * @throws SpicaDatabaseException if there is any problem with database connection or query
     * @param  string $pageId
     * @return SpicaRowList
     */
    public function findNotesByPageId($pageId)
    {
        try
        {
            $rowList = new SpicaRowList();
            $sql     = sprintf('SELECT note_id, note_content, note_dtime, note_username
                                FROM notes
                                WHERE page_id = %s AND note_status = 1
                                ORDER BY note_dtime DESC', $pageId);
            $stmt    = $this->ds->createStatement();
            $notes   = $stmt->fetchAll($sql);
            $rowList->fill($notes);
        }
        catch (SpicaDatabaseException $e)
        {
            $rowList->setReadable(false);
            $rowList->setMessage($e->getMessage());
            Spica::logException($e);
        }

        $stmt->close();
        return $rowList;
    }

    /**
     * Finds page content by ID.
     *
     * @throws SpicaDatabaseException if there is any problem with database connection or query
     * @param  int $pageId
     * @return SpicaRowList
     */
    public function findByPageId($pageId)
    {

    }

    /**
     * Finds page content by a page name.
     *
     * @param  string $section Page section
     * @param  int $pageName
     * @return SpicaRowList
     */
    public function findByPageName($section, $pageName)
    {
        try
        {
            $rowList  = new SpicaRowList();
            $section  = $this->ds->quote($section);
            $pageName = $this->ds->quote($pageName);
            $sql      = sprintf('SELECT page_id, page_title,
                                        page_content, page_header1,
                                        page_desc, page_dtime
                                 FROM manual_pages
                                 WHERE page_section = %s
                                 AND page_name = %s', "'".$section."'", "'".$pageName."'");
            $stmt = $this->ds->createStatement();
            $page = $stmt->fetchOne($sql);
            $stmt->close();
            $rowList->fill($page);
        }
        catch (SpicaDatabaseException $e)
        {
            $rowList->setReadable(false);
            $rowList->setMessage($e->getMessage());
            Spica::logException($e);
        }

        return $rowList;
    }

    /**
     * Finds page title by a page ID.
     *
     * @param  string $section Page section
     * @param  int    $pageName
     * @return SpicaRowList
     */
    public function findPageTitleByPageName($section, $pageName)
    {
        try
        {
            $rowList  = new SpicaRowList();
            $section  = $this->ds->quote($section);
            $pageName = $this->ds->quote($pageName);
            $sql      = sprintf('SELECT page_title
                                 FROM manual_pages
                                 WHERE page_section = %s
                                 AND page_name = %s', "'".$section."'", "'".$pageName."'");
            $stmt = $this->ds->createStatement();
            $page = $stmt->fetchOne($sql);
            $stmt->close();
            $rowList->fill($page);
        }
        catch (SpicaDatabaseException $e)
        {
            $rowList->setReadable(false);
            $rowList->setMessage($e->getMessage());
            Spica::logException($e);
            Spica::logError($e->getNativeMessage());
        }

        return $rowList;
    }
}

?>